package com.zhugang.week13.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program algorithms
 * @description: threeSum
 * @author: chanzhugang
 * @create: 2022/09/17 23:52
 */
public class ThreeSum {

    /**
     * 15 三数之和
     * https://leetcode.cn/problems/3sum/
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> threeSum(int[] nums) {
        // nums[i] + nums[j] + nums[k] == 0 且 i != j, i != k, j != k
        // 双指针排序, 先遍历外层循环，内层循环用双指针
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);

        int n = nums.length;

        for (int i = 0; i < n; i++) {
            if (i != 0 && nums[i - 1] == nums[i]) {
                // 相邻元素不能重复
                continue;
            }

            int j = i + 1;
            int k = n - 1;
            while (j < k) {
                if (j >= i + 2 && nums[j - 1] == nums[j]) {
                    // 相邻元素不能重复
                    j++;
                    continue;
                }
                if (k <= n - 2 && nums[k] == nums[k + 1]) {
                    // 相邻元素不能重复
                    k--;
                    continue;
                }

                int target = -(nums[j] + nums[k]);
                if (nums[i] == target) {
                    result.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    j++;
                    k--;
                } else if (nums[i] < target) {
                    j++;
                } else {
                    k--;
                }
            }
        }
        return result;
    }
}